import HandleBtn from '@/components/HandleBar/btn';
import type { ProColumns } from '@/components/Pro/';
import { ProTable } from '@/components/Pro/';
import { parseArray } from '@/pages/Statistics/Battery/utils';
import { TreeNode } from '@/pages/Statistics/ElectricityConsumption/help';
import { rowToColumns } from '@/pages/Statistics/TransferEfficiency/utils';
import {
  statisticEfficiencyControllerExportEfficiencyDatas as downloadFile,
  statisticEfficiencyControllerGetDatEfficiencyPage as getList,
} from '@/services/ess/statisticEfficiency';
import { downloadFetch } from '@/utils/downloadFile';
import { useIntl } from '@umijs/max';
import { DatePickerProps, message } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { useModel } from 'umi';
import './Common.less';

type areaColumnsType = {
  title: string;
  dataIndex: string;
  key: string;
  hideInSearch: boolean;
};
const TableList: React.FC<{
  dateType: number;
  deviceInfo: API.DeviceInfo[];
}> = ({ dateType, deviceInfo }, ref) => {
  const intl = useIntl();

  const tableColumnsMap = new Map<string, string>([
    ['dischargeEnergy', `${intl.formatMessage({ id: 'statistics.common.discharge' })}(kWh)`],
    ['chargeEnergy', `${intl.formatMessage({ id: 'statistics.common.charge' })}(kWh)`],
    ['convertRatio', `${intl.formatMessage({ id: 'statistics.analyze.chargeTrans' })}(%)`],
    ['pocOnGridEnergy', `${intl.formatMessage({ id: 'batteryVoltage.safe.onGrid' })}(kWh)`],
    ['pocOffGridEnergy', `${intl.formatMessage({ id: 'batteryVoltage.safe.offGrid' })}(kWh)`],
    ['pocConvertRatio', `${intl.formatMessage({ id: 'statistics.analyze.netTrans' })}(%)`],
  ]);
  const { initialState } = useModel('@@initialState');
  const formRef = useRef(null);
  const { stationId } = useModel('@@initialState')?.initialState || {};
  const [type, setType] = useState('1');
  const dateTypeStr = (dateType === 1 && 'day') || (dateType === 2 && 'month') || 'year';
  const [deviceVal, setDeviceVal] = useState();
  const [areaFlag, setAreaFlag] = useState(false);
  const [stationFlag, setStationFlag] = useState(true);

  const selectedType = useRef(null);
  const treeData = useRef(deviceInfo);
  /**
   * 获得对应的columns
   * @param keys
   */
  const getAreaColumns = (keys: string[]): areaColumnsType[] => {
    return keys.map((item: string) => {
      const nameArr = item.split('_');
      console.log('nameArr-----------', nameArr);
      return {
        title: `${nameArr[0]}_${tableColumnsMap.get(nameArr[1])}`,
        dataIndex: item,
        key: item,
        hideInSearch: true,
      };
    });
  };
  /**
   * 获得禁用列表
   * @param Nodes
   */
  const setDisabled = (Nodes: TreeNode[]): TreeNode[] => {
    return Nodes.map((node) => {
      const newNode: TreeNode = {
        ...node,
        disabled: selectedType.current === null ? false : node.nodeType !== selectedType.current,
      };
      if (newNode.subDevices) {
        newNode.subDevices = setDisabled(newNode.subDevices);
      }
      return newNode;
    });
  };
  const disabledDate: DatePickerProps['disabledDate'] = (current, { from }) => {
    const disabled = current && current >= moment().endOf('day');

    if (from) {
      if (dateType === 1) return disabled || Math.abs(current.diff(from, 'day')) >= 180;
      if (dateType === 2) return disabled || Math.abs(current.diff(from, 'month')) >= 36;
      if (dateType === 3) return disabled || Math.abs(current.diff(from, 'years')) >= 10;
    }

    return disabled;
  };

  const initialValue = () => {
    if (dateType === 1) return [moment().subtract(32, 'days'), moment().subtract(1, 'days')];
    if (dateType === 2) return [moment().subtract(12, 'months'), moment().subtract(1, 'months')];
    if (dateType === 3) return [moment().subtract(5, 'years'), moment().subtract(1, 'years')];
  };
  useEffect(() => {
    if (deviceInfo && deviceInfo.length) {
      setDeviceVal(deviceInfo[0]?.uniqueId);
      selectedType.current = 'ROOT';
      treeData.current = setDisabled([deviceInfo[0]]);
    }
  }, [deviceInfo]);
  const baseColumns: ProColumns<API.StatisticEfficiency>[] = [
    {
      title: intl.formatMessage({ id: 'batteryVoltage.tableNo' }),
      dataIndex: 'pageIndex',
      valueType: 'index',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'statistics.income.select' }),
      dataIndex: 'dataDate',
      initialValue: initialValue(),
      fieldProps: {
        disabledDate: disabledDate,
        allowClear: false,
      },
      valueType:
        (dateType === 2 && 'dateMonthRange') || (dateType === 3 && 'dateYearRange') || 'dateRange',
      search: {
        transform: (value) => {
          const dateFormat =
            (dateType === 2 && 'YYYY-MM') || (dateType === 3 && 'YYYY') || 'YYYY-MM-DD';
          return {
            startDate: moment(value[0]).format(dateFormat),
            endDate: moment(value[1]).format(dateFormat),
          };
        },
      },
      hideInTable: true,
    },
    // {
    //   title: intl.formatMessage({ id: 'statistics.work.dimensions' }),
    //   dataIndex: 'dataType',
    //   hideInTable: true,
    //   initialValue: '1',
    //   valueEnum: {
    //     1: {
    //       text: intl.formatMessage({ id: 'statistics.work.station' }),
    //     },
    //     2: {
    //       text: intl.formatMessage({ id: 'batteryVoltage.safe.stack' }),
    //     },
    //   },
    //   fieldProps: {
    //     allowClear: false,
    //     onChange: (v) => {
    //       setType(v);
    //     },
    //   },
    // },
    {
      title: intl.formatMessage({ id: 'statistics.work.dimensions' }),
      dataIndex: 'code',
      valueType: 'treeSelect',
      hideInTable: true,
      initialValue: deviceVal,
      fieldProps: {
        allowClear: false,
        value: deviceVal,
        options: treeData?.current || deviceInfo,
        multiple: true,
        changeOnSelect: true,
        maxTagCount: 2,
        fieldNames: {
          label: 'deviceName',
          value: 'uniqueId',
          children: 'subDevices',
        },
        onSelect: (...args) => {
          let selectOptions = args[1];
          if (selectedType.current === null && selectOptions?.nodeType) {
            selectedType.current = selectOptions?.nodeType;
          }
          // setDeviceTree(setDisabled([deviceTree[0]]));
          treeData.current = setDisabled([treeData?.current[0]]);
        },
        onChange: (...args) => {
          let selectedOptions = args[1];
          setDeviceVal(args[0]);
          if (!selectedOptions.length) {
            //清除后不再做相应限制
            selectedType.current = null;
            // setDeviceTree(setDisabled([deviceTree[0]]));
            treeData.current = setDisabled([treeData?.current[0]]);
          }
          let hasAreaNode: boolean = false;
          let hasStationNode: boolean = false;
          const ans = parseArray(args[0]);
          if (ans.nodeType.length) {
            hasAreaNode = ans.nodeType.some((item: string) => {
              return item === 'AREA';
            });
            hasStationNode = ans.nodeType.some((item: string) => {
              return item === 'ROOT';
            });
          }
          setType(hasAreaNode ? '3' : hasStationNode ? '1' : '2');
          setAreaFlag(hasAreaNode);
          setStationFlag(hasStationNode);
        },
      },
    },
    {
      title: intl.formatMessage({ id: 'statistics.common.period' }),
      dataIndex: (dateType === 2 && 'dataMonth') || (dateType === 3 && 'dataYear') || 'dataDate',
      hideInSearch: true,
      width: 100,
    },
  ];
  const stationColumns = [
    {
      title: `${intl.formatMessage({ id: 'statistics.common.discharge' })}(kWh)`,
      dataIndex: 'dischargeEnergy',
      hideInSearch: true,
      width: 130,
    },
    {
      title: `${intl.formatMessage({ id: 'statistics.common.charge' })}(kWh)`,
      dataIndex: 'chargeEnergy',
      hideInSearch: true,
      width: 130,
    },
    {
      title: `${intl.formatMessage({ id: 'statistics.analyze.chargeTrans' })}(%)`,
      dataIndex: 'convertRatio',
      hideInSearch: true,
      width: 150,
    },
    {
      title: `${intl.formatMessage({ id: 'batteryVoltage.safe.onGrid' })}(kWh)`,
      dataIndex: 'pocOnGridEnergy',
      hideInSearch: true,
      width: 130,
    },
    {
      title: `${intl.formatMessage({ id: 'batteryVoltage.safe.offGrid' })}(kWh)`,
      dataIndex: 'pocOffGridEnergy',
      hideInSearch: true,
      width: 130,
    },
    {
      title: `${intl.formatMessage({ id: 'statistics.analyze.netTrans' })}(%)`,
      dataIndex: 'pocConvertRatio',
      hideInSearch: true,
      width: 150,
    },
  ];
  const [dynamicColumns, setDynamicColumns] = useState<ProColumns[]>([]);
  const columns = baseColumns.concat(dynamicColumns);
  useImperativeHandle(ref, () => ({
    download: () => {
      const value = formRef?.current?.getFieldsFormatValue() || {};
      if (deviceVal) {
        const ans = parseArray(deviceVal);
        value.code = ans.id.join(',');
        value.pageSize = stationFlag ? 10 : ans.id.length * 10;
      } else {
        value.code = initialState?.stationId;
      }
      delete value.type;
      value.areaFlag = areaFlag;
      value.dataType = type;
      downloadFetch(downloadFile, { stationId: stationId, dateType: dateTypeStr, ...value });
    },
  }));

  return (
    <div>
      <ProTable<API.StatisticEfficiency, API.PageParams>
        headerTitle=" "
        style={{ position: 'relative', zIndex: '10' }}
        formRef={formRef}
        onReset={() => {
          setDeviceVal(treeData?.current[0]?.uniqueId);
          setStationFlag(true);
          setAreaFlag(false);
          setType('1');
          selectedType.current = 'ROOT';
          treeData.current = setDisabled([treeData?.current[0]]);
        }}
        rowKey="id"
        request={async (params) => {
          let len = 1;
          if (deviceVal?.length) {
            len = deviceVal?.length;
            const ans = parseArray(deviceVal);
            params.code = ans.id.join(',');
            params.pageSize = stationFlag ? 20 : ans.id.length * 20;
          } else {
            message.warning(intl.formatMessage({ id: 'statistics.analyze.objWarning' }));
            params.areaFlag = false;
            return false;
          }
          delete params.type;
          params.areaFlag = areaFlag;
          params.dataType = type;
          const res = await getList(params);
          const forRes = rowToColumns(res.data.records, areaFlag);
          const keys = _.slice(Object.keys(forRes[0]), 2);
          if (stationFlag) {
            setDynamicColumns(stationColumns);
          } else {
            setDynamicColumns(getAreaColumns(keys));
          }
          return {
            success: res.success,
            data: stationFlag ? res.data.records : forRes,
            total: stationFlag ? res.data.total : Number(res.data.total) / len,
          };
        }}
        params={{
          dateType: dateTypeStr,
        }}
        columns={columns}
        search={{
          className: 'searchPosInline',
        }}
        toolbar={{
          className: 'toobalrZindex',
          actions: [
            // eslint-disable-next-line react/button-has-type
          ],
        }}
      />
    </div>
  );
};

export type ToolBarProps = {
  tableRef: React.MutableRefObject<null>;
};
const ToolBarRender: React.FC<ToolBarProps> = ({ tableRef }) => {
  const intl = useIntl();
  return (
    <>
      <HandleBtn handleType="export" key="export" onClick={() => tableRef?.current?.download()}>
        {intl.formatMessage({ id: 'statistics.common.export' })}
      </HandleBtn>
    </>
  );
};

export default forwardRef(TableList);
export { ToolBarRender };
